package com.hyphenate.easeui.utils.permssion;

import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;

/**
 * Description:
 * Author:洪培林
 * Date:2017-09-27
 */

class PermissionFragmentDelegate {
    private OnRequestPermissionsResultListener mListener;
    private String[] mPermissions;
    private boolean isAttach;
    private Object fragment;

    PermissionFragmentDelegate(Object fragment) {
        this.fragment = fragment;
    }

    public void onAttach() {
        isAttach = true;
        if (mListener != null) {
            requestPermissions(mPermissions);
        }
    }

    public void request(String[] permissions, OnRequestPermissionsResultListener listener) {
        if (listener != null) {
            mPermissions = permissions;
            mListener = listener;
            if (isAttach) {
                requestPermissions(mPermissions);
            }
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (mListener != null && requestCode == Guardian.FRAGMENT_REQUEST_CODE) {
            mListener.onRequestPermissionsResult(permissions, grantResults);
        }
    }

    private void requestPermissions(@NonNull String[] permissions) {
        if (fragment instanceof Fragment) {
            ((Fragment) fragment).requestPermissions(permissions, Guardian.FRAGMENT_REQUEST_CODE);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (fragment instanceof android.app.Fragment)) {
            ((android.app.Fragment) fragment).requestPermissions(permissions, Guardian.FRAGMENT_REQUEST_CODE);
        }
    }

    public void onDetach() {
        mListener = null;
        mPermissions = null;
        isAttach = false;
        fragment = null;
    }
}
